import React, { createContext, useState, useContext } from "react";
import { useThemeManager } from "../hooks/useThemeManager";

type Theme = "light" | "dark";

interface ThemeContextType {
  theme: Theme;
  toggleTheme: () => void;
}

// 建立了一个ThemeContext
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

// 定义了一个ThemeProvider组件，它管理主题状态并提供切换主题的方法。
export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  //方式 1.Context
  //   const [theme, setTheme] = useState<Theme>("light");
  //   const toggleTheme = () => {
  //     setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
  //   };
  //   return (
  //     <ThemeContext.Provider value={{ theme, toggleTheme }}>
  //       {children}
  //     </ThemeContext.Provider>
  //   );

  // 方式2.结合自定义Hooks和Context
  const themeManager = useThemeManager();
  return (
    <ThemeContext.Provider value={themeManager}>
      {children}
    </ThemeContext.Provider>
  );
};

// 建立了一个自定义Hook useTheme，用于在其他组件中方便地访问主题状态和切换方法
export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error("useTheme must be used within a ThemeProvider");
  }
  return context;
};
